package com.next

import sun.misc.BASE64Decoder
import grails.converters.JSON
import grails.gorm.transactions.Transactional
import groovy.json.JsonOutput
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked

@Transactional
@CompileStatic
@TypeChecked
class AttachmentsService
{
    static scope = "singleton"

    def writeImage(Attachments attachment, String webrootDir)
    {
        String sImage = attachment['data']
        BASE64Decoder decoder = new BASE64Decoder()
        byte[] bImage = decoder.decodeBuffer(sImage)

        File fileImage = new File(webrootDir, "files/images/${attachment.fileName}.jpg")

        fileImage.append(bImage)
    }

    def getAddressByLocation(String latitude, String longitude)
    {
        URL url = new URL("http://api.map.baidu.com/geocoder/v2/?ak=C93b5178d7a8ebdb830b9b557abce78b&location=" + latitude + "," + longitude + "&output=json&pois=0")
        HttpURLConnection connection = (HttpURLConnection) url.openConnection()
        connection.setDoOutput(true)
        connection.setRequestMethod("GET")
        def response = connection.inputStream.withReader("UTF-8") { Reader reader -> reader.text }
        def result = JSON.parse(response).getAt("result")
        return result
    }
}
